<?php

namespace App\Http\Controllers\Api\SmallApp\User;

use App\Http\Controllers\Common\ApiController;
use App\Models\Cert\CertDriver;
use App\Models\Cert\CertGo;
use App\Models\Cert\CertGoOther;
use App\Models\SerialNumber\SerialNumber;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class UserInfoController extends ApiController {

    public function userInfo(Request $request) {
        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->with(['getDriverInfo','getGo','getGoOther'])->first();
        if(empty($user)) {
            //return responseFail('用户无效！');
            return responseSuccess(['is_real'=>false],0,100000,[],false);
        }
        else{
            $user->is_active = !empty($user->serial_number);
            $user->is_real = true;
            return responseSuccess($user->toArray());
        }
    }

    public function updateUserInfo(Request $request) {
        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->with('getDriverInfo')->first();
        if(empty($user)) return responseFail('用户无效！');

        $id_card = $request->input('id_card');
        $name = $request->input('name');
        $phone = $request->input('phone');

        $this->validate($request, [
            'id_card'=>'required',
            'name'=>'required',
            //'phone'=>'required',
        ]);

        $user->phone = $phone;
        //$user->save();

        $driver = CertDriver::where(['user_id'=>$id])->first();
        if(empty($user)) return responseFail('驾照信息无效！');

        $driver->name = $name;
        $driver->id_card = $id_card;
        $driver->save();
        return responseSuccess();
    }

    public function active(Request $request) {
        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->with('getDriverInfo')->first();
        if(empty($user)) return responseFail('用户无效！');

        $serial_number = $request->input('serial_number');
        $this->validate($request, [
            'serial_number'=>'required',
        ],[]);

        if(!CertDriver::where('user_id',$id)->exists()){
            return responseFail('请上传驾照！');
        }
        if(!CertGo::where('user_id',$id)->exists()){
            return responseFail('请上传驾驶证-主页！');
        }
        if(!CertGoOther::where('user_id',$id)->exists()){
            return responseFail('请上传驾驶证-副页！');
        }


        try {
            DB::beginTransaction();

            $user->serial_number= $serial_number;
            $user->active_time = date('Y-m-d H:i:s');
            $user->save();

            $record = SerialNumber::where(compact('serial_number'))->first();
            $record->user_id = $user->id;
            $record->status =1;
            $record->save();

            DB::commit();
            return responseSuccess();
        }catch (\Exception $e){
            DB::rollBack();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }
    }

    public function changePhone(Request $request) {

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user)) return responseFail('用户无效！');

        $phone = $request->input('phone');
        $verify_code = $request->input('verify_code');
        $this->validate($request, [
            'phone'=>'required|unique:App\Models\User\User,phone|regex:/^1[3456789]\d{9}$/',
            'verify_code'=>'required|integer',
            //confirmed
        ]);
        if(env('APP_ENV')!='test'){
            $key = "verifyCode:$phone:$verify_code";
            if(Redis::exists($key)!=1){
                return responseFail('验证码错误！');
            }
        }

        $user->phone = $phone;
        $user->save();
        return responseSuccess($user->toArray());
    }

    public function changePassword(Request $request) {
        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user)) return responseFail('用户无效！');

        $old_password = $request->input('old_password');
        $password = $request->input('password');
        $this->validate($request, [
            'password'=>'required|confirmed|between:8,16|regex:/^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S+$/',
        ],[
            'password.between'=>'密码必须包含数字和字符且8-16位',
            'password.regex'=>'密码必须包含数字和字符且8-16位'
        ]);

        if($user->password!=md5($old_password))
            return responseFail('原密码错误！');
        $user->password = md5($password);
        $user->save();
        return responseSuccess();
    }

    public function checkSerialNumber(Request $request) {
        $serial_number = $request->input('serial_number');
        $record = SerialNumber::where(compact('serial_number'))->first();
        if(empty($record)){
            return responseFail('很遗憾，序列号无效！');
        }

        if($record->user_id!=0){
            return responseFail('该序列号已经被激活过了!');
        }
        if($record->status==1){
            return responseFail('该序列号已经被送出!');
        }

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user)) return responseFail('用户无效！');

        if(!empty($user->serial_number))
            return responseFail('您已经激活过了，您的序列号为：'.$user->serial_number);

        return responseSuccess();
    }

    public function getWxInfo(Request $request) {

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user)) return responseFail('用户无效！');


        $wxInfo = $request->input('wx_info');

        $wxInfo = json_decode($wxInfo,true,JSON_UNESCAPED_UNICODE);
        $wx_nickname = $wxInfo['nickName'];
        $wx_avatar = $wxInfo['avatarUrl'];

        $user->wx_nickname = $wx_nickname;
        $user->wx_avatar = $wx_avatar;
        $user->save();

        //Log::info('wx',compact('wxInfo'));

        /*$code = $request->input('code');
        $this->validate($request, [
            'code'=>'required'
        ]);

        $config = [
            'app_id' => env('WX_SMALL_APPID'),
            'secret' => env('WX_SMALL_SECRET'),
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => storage_path('logs/wechat.log'),
            ],
        ];

        $app = Factory::miniProgram($config);
        $result = $app->auth->session($code);
        Log::info('result',compact('request'));*/
        return responseSuccess($user->toArray());
    }

    public function getDriverInfo(Request $request) {

        $token = $request->header('token');
        $id = checkJWT($token)['id'];

        $user = User::where(compact('id'))->first();
        if(empty($user)) return responseFail('无效用户');

        //type  0 表示行驶证，1 表示驾驶证，2 表示行驶证副页
        $type = $request->input('type',1);

        $this->validate($request, [
            'type'=>'required|integer|between:0,2'
        ]);

        $file = $request->file('file');
        //$file = $request->input('file');
        Log::info('params',$request->input());
        Log::info('file',[$request->file()]);
        Log::info('getRealPath',[$file->getRealPath()]);
        Log::info('getSize',[$file->getSize()]);
        //return responseSuccess(['测试']);

        //Log::info('file',compact('file'));
        //Log::info('file1',$request->input());
        if(empty($file) || !$file->isValid()){
            Log::info('isValid',[$file->isValid()]);
            return responseFail('文件无效！');
        }


        $size =  $file->getSize();

        if($type==0){
            $module = 'go';
        }elseif ($type==1){
            $module = 'driver';
        }else{
            $module = 'goOther';
        }

        try{
            DB::beginTransaction();
            $fileName = $id.'_'.uniqid().'.jpg';
            $middlePath = "/$module/".date('Y-m-d');
            $absDir = Storage::disk('upload')->path($middlePath);
            if(!is_dir($absDir)){mkdir($absDir,0777,true);}

            $imgIsCutSize = $request->input('imgIsCutSize',env('IMG_IS_CUT_SIZE',1024*1024*6));//压缩阈值
            if($size>$imgIsCutSize){
                $imgCutRatio = $request->input('imgCutRatio',env('IMG_CUT_RATION',700));//压缩比
                Log::info('开始压缩文件');
                $rs = Image::make($file->getRealPath())
                    ->resize($imgCutRatio, $imgCutRatio, function ($constraint) {
                        $constraint->aspectRatio();
                    })->save($absDir."/$fileName");
                if($rs === false){
                    return responseFail('图片压缩失败');
                }
                Log::info('压缩完成');
                $filePath = "$middlePath/$fileName";
            }else{
                $filePath = $file->storeAs($middlePath,$fileName,'upload');
            }
            $filePath = '/storage/upload'.$filePath;
            Log::info('filePath',compact('filePath'));

            $imgUrl = asset($filePath);
            //$imgUrl = "http://anquanbao.techbz.cn$filePath";
            Log::info('imgUrl',compact('imgUrl'));
            $url = "https://recognition.image.myqcloud.com/ocr/drivinglicence";
            $argument = [
                'appid'=>env('TENCENT_APPID','1311819953'),
                'type'=>$type,
                'url'=>$imgUrl,
                'bucket'=>'test'
            ];
            Log::info('argument',$argument);
            $argument = json_encode($argument);
            $result = $this->post_url($url, $argument);
            $result = json_decode($result,true,JSON_UNESCAPED_UNICODE);

            if($result['code']!=0 || $result['message']!='OK'){
                Log::error('类型是'.$type,$result);
                return responseFail('识别错误，请重新上传！',$result);
            }

            if($result['code']==0 && $result['message']=='OK'){
                Log::info('类型是'.$type,$result);
                //驾驶证
                if($type==1){
                    $record = $this->generateDriverCert($result,$id,$filePath);
                    $user->cert_driver_id = $record->id;
                    $user->save();
                }
                //行驶证
                elseif ($type==0){
                    $record = $this->generateGoCert($result,$id,$filePath);
                    $user->cert_go_id = $record->id;
                    $user->save();
                }
                //行驶证副页
                else{
                    $record = $this->generateGoOtherCert($result,$id,$filePath);
                    $user->cert_go_other_id = $record->id;
                    $user->save();
                }
                $data = [];
                $msg = '识别成功！';
                $status = true;
                $code = 0;
                $info = compact('data','msg','status','code');
                //return $info;
                DB::commit();
                //return responseSuccess($user->toArray(),1,'识别成功！',[],true,['Content-Type: application/json;charset=utf-8'],);
                return responseSuccess([],0,'识别成功！');
            }else{
                DB::rollBack();
                return responseFail('未知问题！');
            }

        }catch(\Exception $e){
            DB::rollBack();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }
    }



    protected function generateDriverCert(array $result,$user_id,$img_url){

        $seq = $result['seq'];
        $items = $result['data']['items'];
        $info = compact('seq','img_url','user_id');
        foreach ($items as $item) {
            if($item['item']=='证号') $info['id_card'] = $item['itemstring'];
            elseif ($item['item']=='国籍') $info['country'] = $item['itemstring'];
            elseif ($item['item']=='性别') $info['gender'] = $item['itemstring'];
            elseif ($item['item']=='姓名') $info['name'] = $item['itemstring'];
            elseif ($item['item']=='出生日期') $info['birthday'] = $item['itemstring'];
            elseif ($item['item']=='领证日期') $info['get_cert_day'] = $item['itemstring'];
            elseif ($item['item']=='准驾车型') $info['allow_car_type'] = $item['itemstring'];
            elseif ($item['item']=='起始日期') $info['start_day'] = $item['itemstring'];
            elseif ($item['item']=='有效日期') $info['effective_day'] = $item['itemstring'];
            elseif ($item['item']=='住址') $info['address'] = $item['itemstring'];
            elseif ($item['item']=='发证单位') $info['giving_unit'] = $item['itemstring'];
            elseif ($item['item']=='红章') $info['hong_zhang'] = $item['itemstring'];
            else continue;
        }

        /*$id_card = $items[0]['itemstring'];
        $country = $items[1]['itemstring'];
        $gender = $items[2]['itemstring'];
        $name = $items[3]['itemstring'];
        $birthday = $items[4]['itemstring'];
        $get_cert_day = $items[5]['itemstring'];
        $allow_car_type = $items[6]['itemstring'];
        $start_day = $items[7]['itemstring'];
        $effective_day = $items[8]['itemstring'];
        $address = $items[9]['itemstring'];
        $giving_unit = $items[10]['itemstring'];
        $hong_zhang = $items[11]['itemstring'];
        $info = compact('seq','id_card','country','gender','name','birthday','get_cert_day','allow_car_type','start_day',
            'effective_day','address','giving_unit','hong_zhang','user_id','img_url');*/
        return CertDriver::updateOrCreate(compact('user_id'),$info);
    }

    protected function generateGoCert(array $result,$user_id,$img_url){

        $seq = $result['seq'];
        $items = $result['data']['items'];
        $info = compact('seq','img_url','user_id');
        foreach ($items as $item) {
            if($item['item']=='车牌号码') $info['car_number'] = $item['itemstring'];
            elseif ($item['item']=='车辆类型') $info['car_type'] = $item['itemstring'];
            elseif ($item['item']=='品牌型号') $info['car_brand'] = $item['itemstring'];
            elseif ($item['item']=='使用性质') $info['use_way'] = $item['itemstring'];
            elseif ($item['item']=='识别代码') $info['spot_code'] = $item['itemstring'];
            elseif ($item['item']=='发动机号') $info['engine_number'] = $item['itemstring'];
            elseif ($item['item']=='注册日期') $info['register_day'] = $item['itemstring'];
            elseif ($item['item']=='发证日期') $info['giving_day'] = $item['itemstring'];
            elseif ($item['item']=='所有人') $info['belong_to'] = $item['itemstring'];
            elseif ($item['item']=='住址') $info['address'] = $item['itemstring'];
            elseif ($item['item']=='发证单位') $info['giving_unit'] = $item['itemstring'];
            elseif ($item['item']=='红章') $info['hong_zhang'] = $item['itemstring'];
            else continue;
        }

        /*$car_number = $items[0]['itemstring'];
        $car_type = $items[1]['itemstring'];
        $car_brand = $items[2]['itemstring'];
        $use_way = $items[3]['itemstring'];
        $spot_code = $items[4]['itemstring'];
        $engine_number = $items[5]['itemstring'];
        $register_day = $items[6]['itemstring'];
        $giving_day = $items[7]['itemstring'];
        $belong_to = $items[8]['itemstring'];
        $address = $items[9]['itemstring'];
        $giving_unit = $items[10]['itemstring'];
        $hong_zhang = $items[11]['itemstring'];
        $info = compact('seq','car_number','car_type','car_brand','use_way','spot_code','engine_number','register_day','giving_day',
            'belong_to','address','giving_unit','hong_zhang','user_id','img_url');*/
        return CertGo::updateOrCreate(compact('user_id'),$info);
    }

    protected function generateGoOtherCert(array $result,$user_id,$img_url){

        $seq = $result['seq'];
        $items = $result['data']['items'];
        $info = compact('seq','img_url','user_id');
        foreach ($items as $item) {
            if($item['item']=='档案编号') $info['file_number'] = $item['itemstring'];
            elseif ($item['item']=='号牌号码') $info['car_number'] = $item['itemstring'];
            elseif ($item['item']=='总质量') $info['all_weight'] = $item['itemstring'];
            elseif ($item['item']=='核定载人数') $info['carry_number'] = $item['itemstring'];
            elseif ($item['item']=='整备质量') $info['zhengbei_weight'] = $item['itemstring'];
            elseif ($item['item']=='外廓尺寸') $info['waikuo_size'] = $item['itemstring'];
            elseif ($item['item']=='检验记录') $info['inspection_record'] = $item['itemstring'];
            elseif ($item['item']=='核定载质量') $info['he_weight'] = $item['itemstring'];
            elseif ($item['item']=='准牵引总质量') $info['qianyin_weight'] = $item['itemstring'];
            else continue;
        }
        /*$file_number = $items[0]['itemstring'];
        $car_number = $items[1]['itemstring'];
        $all_weight = $items[2]['itemstring'];
        $carry_number = $items[3]['itemstring'];
        $zhengbei_weight = $items[4]['itemstring'];
        $waikuo_size = $items[5]['itemstring'];
        $inspection_record = $items[6]['itemstring'];
        $he_weight = $items[7]['itemstring'];
        $qianyin_weight = $items[8]['itemstring'];

        $info = compact('seq','car_number','file_number','all_weight','carry_number','zhengbei_weight','waikuo_size',
            'inspection_record','he_weight', 'qianyin_weight','user_id','img_url');*/
        return CertGoOther::updateOrCreate(compact('user_id'),$info);
    }

    protected function post_url($durl, $post_data){
        //请求头配置
        $headers = array(
            "host:recognition.image.myqcloud.com",
            "content-type:application/json",
            "authorization:".getTencentSign()['signStr'], //鉴权算法 下方查看
        );
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $durl);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
}
